<template>
    <el-popover placement="bottom" :width="270" trigger="click" :popper-style="popperStyle" :teleported="false">
      <template #reference>
        <slot name="cont"></slot>
      </template>
      <div class="title">最近选择</div>
      <div class="hot-city">
        <el-tag size="small" v-for="(item,index) in hotCityReadonly" @click="handleTag(item)" :key="index" style="margin: 4px;cursor: pointer;">
          {{ item.label }}
        </el-tag>
      </div>
      <div class="city-search">
        <el-icon><Search /></el-icon>
        <el-select
        v-model="valueRef"
        filterable
        remote
        reserve-keyword
        placeholder="请搜索需要定位的城市"
        :remote-method="remoteMethod"
        :loading="loadingRef"
        style="width: 240px"
        @change="handleChange"
      >
        <el-option
          v-for="item in optionsRef"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </div>
    </el-popover>
</template>
<script setup>
import { ref , defineEmits , inject , defineProps, watch } from 'vue';
import { Search } from '@element-plus/icons-vue'
import useSymbols from '../../compostions/useSymbols';
import {
    getSearchCityApi
} from '../../apis/weatherApi.js';

const { hotCityReadonly , setHotCity} = inject(useSymbols);

const emit = defineEmits(['onSelectedCity'])

const valueRef = ref();
const loadingRef = ref(false);
const optionsRef = ref([])

const popperStyle = {
    borderRadius: '15px',
    boxShadow:'0 0 0 #FFF',
}

const remoteMethod = (query) => {
    if (query) {
        loadingRef.value = true
        setTimeout(() => {
            loadingRef.value = false
          getList(query);
        }, 200)
  } else {
    optionsRef.value = []
  }
}
const getList = async (v) => {
    const {data} = await getSearchCityApi(v);
    optionsRef.value = data.city_list.map((item)=>({label:item.name,value:item.cityId,localPname:item.localPname}))
}

const handleChange = (v) => {
  const item = optionsRef.value.find((item) => item.value === v);
  setHotCity({ label: item ? item.label : '', value: v ,localPname:item?item.localPname:''});
  emit('onSelectedCity', { cityId: v, city: item ? item.label : '', localPname: item ? item.localPname : '' });
}
const handleTag = ({ label, value , localPname}) => {
  emit('onSelectedCity', { cityId: value, city: label, localPname });
}
</script>
<style scoped lang="less">
 .title{
    color: #565656;
    padding: 4px 0 8px 0;
    font-size: 14px;
}
.hot-city{
  margin-bottom: 8px;
  margin-left: -4px;
  margin-right: -4px;
}
.city-search{
    display: flex;
    align-items: center;
    border-radius: 15px;
    border: 1px solid var(--el-border-color);
    overflow: hidden;
    padding-left: 8px;
    /deep/.el-select__wrapper{
        box-shadow:0 0 0 #fff;
    }
}
</style>